<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '编辑信息',
  },
}
</route>

<template>
  <view class="edit-profile">
    <wd-img-cropper
      v-model="show"
      :img-src="src"
      @confirm="handleConfirmAvatar"
      @cancel="handleCancel"
    ></wd-img-cropper>
    <wd-datetime-picker
      v-model="birthday"
      ref="birthdayPickerRef"
      style="position: absolute; top: 500rpx; left: 800rpx; z-index: 1"
      type="date"
      :minDate="new Date('1920-01-01T00:00:00Z').getTime()"
      :maxDate="new Date().getTime()"
      label="生日"
      @confirm="handleConfirmBirthday"
    />
    <wd-picker
      style="position: absolute; top: 500rpx; left: 800rpx; z-index: 1"
      ref="genderPickerRef"
      :columns="columns"
      label=""
      v-model="genderValue"
      @confirm="handleConfirm"
    />
    <view>
      <!-- 头像上传 -->
      <view class="profile">
        <view class="avatar-info" @click="upload">
          <wd-img :width="60" :height="60" round :src="form.avatar" />
          <view class="avatar-text">编辑头像</view>
        </view>

        <view class="info-card">
          <view class="info-item">
            <view class="info-lable">昵称</view>
            <view class="info-text">
              <input
                style="font-size: 24rpx"
                v-model="form.nickname"
                placeholder=""
                placeholder-class="input-placeholder"
              />
            </view>
          </view>

          <view class="info-item" @click="openGenderPicker">
            <view class="info-lable">性别</view>
            <view class="info-text">{{ genderMap[form.gender] }}</view>
            <view class="tabbar-youjiantou iconfont info-icon"></view>
          </view>

          <view class="info-item" @click="openBirthdayPicker">
            <view class="info-lable">生日</view>
            <view class="info-text">
              {{ birthday ? formatDate(form.birthday, 'YYYY-MM-DD') : '保密' }}
            </view>
            <view class="tabbar-youjiantou iconfont info-icon"></view>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-footer">
        <wd-button
          type="primary"
          block
          :loading="isSubmitting"
          custom-class="submit-btn"
          @click="handleSubmit"
        >
          保存修改
        </wd-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/store/user'
import { formatDate } from '@/utils/index'
import { putCustomerInfo } from '@/service/user/info'
import { useToast } from 'wot-design-uni'

const userStore = useUserStore()
const toast = useToast()
const isSubmitting = ref(false)
const birthday = ref(userStore.userInfo.birthday)
const columns = ref(['男', '女', '保密'])
const genderMap = {
  0: '女',
  1: '男',
  2: '保密',
}
const genderValue = ref('选项1')
function handleCancel(event) {
  console.log('取消', event)
}
const src = ref<string>('')
const imgSrc = ref<string>('')
const show = ref<boolean>(false)

function upload() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0]
      src.value = tempFilePaths
      show.value = true
    },
  })
}
function handleConfirmAvatar(event) {
  const { tempFilePath } = event
  imgSrc.value = tempFilePath
}

function handleConfirm({ value }) {
  switch (value) {
    case '男':
      form.value.gender = 1
      break
    case '女':
      form.value.gender = 0
      break
    case '保密':
      form.value.gender = 2
      break
    default:
      form.value.gender = 2
      break
  }
}
// 表单数据
const form = ref({
  avatar: userStore.userInfo.avatarUrl,
  nickname: userStore.userInfo.nickname,
  gender: userStore.userInfo.gender || 0,
  birthday: new Date(userStore.userInfo.birthday),
  region: userStore.userInfo.region || '',
})
const birthdayPickerRef = ref()
const genderPickerRef = ref()

const openBirthdayPicker = () => {
  birthdayPickerRef.value.open()
}
const openGenderPicker = () => {
  genderPickerRef.value.open()
}

const handleConfirmBirthday = ({ value }) => {
  console.log(new Date(value))
  form.value.birthday = value
}

// 提交表单
const handleSubmit = async () => {
  try {
    isSubmitting.value = true

    // 表单验证
    if (!form.value.nickname.trim()) {
      return uni.showToast({ title: '昵称不能为空', icon: 'none' })
    }
    if (imgSrc.value) {
      form.value.avatar = imgSrc.value
    }
    try {
      const obj = {
        ...form.value,
        birthday: formatDate(form.value.birthday, 'YYYY-MM-DD'),
      }
      toast.loading('更新中')
      const { code, data } = await putCustomerInfo(obj)
      if (code === 200 && data) {
        // 关键修改：同步到 Pinia store
        userStore.updateUserInfo({
          avatarUrl: data.avatarUrl, // 映射服务端字段
          nickname: data.nickname,
          gender: Number(data.gender),
          birthday: data.birthday,
        })

        // 保持现有表单更新逻辑
        form.value = {
          avatar: data.avatarUrl,
          nickname: data.nickname,
          gender: Number(data.gender),
          birthday: new Date(data.birthday),
          region: '',
        }

        toast.close()
        setTimeout(() => uni.navigateBack(), 1000)
      } else {
        toast.show('更新失败')
      }
    } catch (error) {
      toast.show('更新失败')
    }
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.edit-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 750rpx;
  max-height: 100vh;
  background-color: #f5f5f5;
}

.profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 30rpx;
  margin-bottom: 20rpx;
  .avatar-info {
    position: relative;
    width: 120rpx;
    overflow: hidden;
    border-radius: 50%;
    .avatar-text {
      position: absolute;
      bottom: 10rpx;
      left: 0;
      z-index: 10;
      width: 100%;
      font-size: 18rpx;
      color: #ffffff;
      text-align: center;
      background-color: rgba($color: #000, $alpha: 0.5);
    }
  }
}

.info-card {
  position: relative;
  width: 650rpx;
  padding: 20rpx;
  margin: 20rpx auto;
  background-color: #ffffff;
  border-radius: 15rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 24rpx 0;
  margin: 10rpx 0;
  border-bottom: 1rpx solid #eee;
  .info-lable {
    width: 90rpx;
    font-size: 24rpx;
    color: #333;
  }
  .info-text {
    width: 540rpx;
    font-size: 24rpx;
    color: #999;
  }
  .info-icon {
    font-size: 24rpx;
    color: #999;
  }
}

.info-item:last-child {
  border-bottom: none; /* 最后一项去掉底部边框 */
}

.submit-footer {
  width: 700rpx;
  margin: 20rpx;
  margin-top: 30rpx;
  :deep() {
    .submit-btn {
      font-size: 24rpx;
      color: #ffffff;
      background-color: $uni-bg-themes;
    }
  }
}

// .submit-btn:hover {
//   background-color: $uni-bg-themes-hover;
// }
</style>
